package com.anming.user.web;

import com.anming.common.enums.ExceptionEnum;
import com.anming.common.exception.LyException;
import com.anming.common.utils.CookieUtils;
import com.anming.user.pojo.User;
import com.anming.user.api.UserInfo;
import com.anming.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author bystander
 * @date 2018/9/29
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 校验数据
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(@PathVariable("data") String data, @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.checkData(data, type));
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @PostMapping("send")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone")String phone) {
        userService.sendVerifyCode(phone);
        return ResponseEntity.noContent().build();
    }

    /**
     * 用户注册
     * @param user
     * @param code
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, @RequestParam("code")String code) {
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PostMapping("login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        //获取浏览器传过来的token值
        String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
        System.out.println("==============login=============="+token);
        if(token != null){
            //验证token值是不是在redis当中
            User user = userService.getUserByRedis(token);
            if(user != null){
                return ResponseEntity.ok().build();
            }
        }
        //登陆操作
        token = userService.queryUser(username, password);
        if (StringUtils.isBlank(token)) {
            throw new LyException(ExceptionEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        //将Token写入cookie中
        CookieUtils.setCookie(request, response, "LY_TOKEN",
                token, 1800, null, true);
        return ResponseEntity.ok().build();
    }

    /**
     * 验证用户信息
     *
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN") String token,
                                               HttpServletRequest request,
                                               HttpServletResponse response) {
        System.out.println("==============verify=============="+token);
        try {
            //从Token中获取用户信息
            User user = userService.getUserByRedis(token);
            if(user==null){
                System.out.println("没有找到用户");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            }
            UserInfo userInfo = new UserInfo(user.getId(),user.getUsername());
            //重新添加到redis中
            userService.addUserByRedis(token,user);
            //将newToken写入cookie中
            CookieUtils.setCookie(request, response, "LY_TOKEN",
                    token, 1800, null, true);
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            //Token无效
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
    }

    /**
     * 注销登录
     *
     * @param response
     * @return
     */
    @GetMapping("logout")
    public ResponseEntity<Void> logout(@CookieValue("LY_TOKEN") String token,HttpServletRequest request,HttpServletResponse response) {
        //String token = request.getParameter("LY_TOKEN");
        if (StringUtils.isNotBlank(token)) {
            CookieUtils.setCookie(request, response, "LY_TOKEN",
                    token, 0, null, true);
            userService.deleteUserByRedis(token);
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }





}
